package list

import (
	"errors"
	"fmt"
	"sync"
	"t/log"
)

type SingleNode struct {
	Data interface{}
	Next *SingleNode
}

type SingleList struct {
	Count int64
	Head *SingleNode
	Tail *SingleNode
	mux sync.Mutex
}

func NewList() *SingleList {
	glist := new(SingleList)
	glist.Count = 0
	glist.Tail = nil
	glist.Head = nil
	return glist
}

//从尾部Append
func (glist *SingleList) Append(data interface{}) error {
	glist.mux.Lock()
	defer glist.mux.Unlock()

	node := new(SingleNode)
	node.Data = data
	node.Next = nil
	if glist.Count == 0 {
		//log.Zlog.Error("head 未创建",zap.String("ss","dd"),zap.Int("ggg",45))
		//return errors.New("head 未创建")
		glist.Head = node
		glist.Tail = node
		glist.Count++
		return nil
	}

	tmpNode := glist.Tail
	glist.Tail = node
	tmpNode.Next = glist.Tail
	glist.Count++
	return nil
}

//弹出尾部
func (glist *SingleList) PopTail() *SingleNode {
	glist.mux.Lock()
	defer glist.mux.Unlock()
	var i int64
	reNode := glist.Tail
	node := glist.Head
	for i=0;i<glist.Count;i++{
		if i==glist.Count-1 {
			node.Next = nil
			glist.Tail = node
			break
		}
		node = node.Next
	}
	glist.Count--
	return reNode
}

//插入
func (glist *SingleList) Insert(data interface{},index int64) error{
	if index>glist.Count{
		log.Zlog.Error("下标超过")
		return errors.New("下标超过")
	}
	node := new(SingleNode)
	node.Data = data
	var i int64
	listNode := glist.Head
	for i = 0; i < index; i++ {
		listNode = listNode.Next
	}

	node.Next = listNode.Next
	listNode.Next = node
	glist.Count++
	return nil
}

//遍历输出
func  (glist *SingleList) PrintNode() {
	var i int64
	node := glist.Head
	for i=0;i<glist.Count;i++{

		fmt.Println(node.Data.(int))
		node = node.Next

	}
}

